const router = require('koa-router')();
const jwt = require('jsonwebtoken');
const verify = require('util').promisify(jwt.verify);
const path = require('path');
const fs = require('fs');
// const sharp = require('sharp');



//获取用户列表
router.get('/getUserList', async (ctx, next) => {
	const token  = ctx.header.authorization;
	const userToken = await verify(token.split(' ')[1], 'test');
	if(!userToken) ctx.body = { success: false, message: "token验证失败" };
	
	let result = await ctx.db.Excute("select * from users");

    ctx.body = { userList: result };
});

//删除用户
router.delete('/delUser', async (ctx, next) => {
	const token  = ctx.header.authorization;
	const userToken = await verify(token.split(' ')[1], 'test');
	if(!userToken) ctx.body = { success: false, message: "token验证失败" };
	
	const userid = ctx.query.id;
	let sqlStr = ("delete from users where user_id=?");
	let result = ctx.db.Excute(sqlStr, [userid]);
	if (result) ctx.body = { success: true, message: '用户删除成功' };
	else ctx.body = { success: false, message: '用户删除失败' };
});

//文件上传
router.post('/upload', async (ctx) => {
	const token  = ctx.header.authorization;
	const userToken = await verify(token.split(' ')[1], 'test');
	if(!userToken) ctx.body = { success: false, message: "token验证失败" };

	const files  = ctx.request.files;
	const file = files.file
	const { filepath } = file;
  
	if (files && files.file) {
	  let folder = '/'; 
	  if (files.file.mimetype === 'application/pdf') {
		folder = '/pdfs';
	  } else if (files.file.mimetype.includes('image')) {
		folder = '/images'; 
	  }
	const prePath = process.cwd() + '/public';
	  // 移动文件至指定文件夹
	  const newFilePath = prePath + folder + '/' + files.file. originalFilename;
	  fs.renameSync(filepath, newFilePath);
  
	  let sqlStr = "insert into files (name, type) values(?, ?)"
	  try {
		let results = await ctx.db.Excute(sqlStr, [files.file.originalFilename, files.file.mimetype]);
  
		if (results){
			ctx.body = {
				success: 'success',
				message: '上传成功',
				fileInfo: {
				  name: files.file.name,
				  type: files.file.type,
				  size: files.file.size,
				  folder: folder
				}
			  };
		} else {
		  ctx.body = '上传失败';
		}
	  } catch (error) {
		console.log(error);
		ctx.body = {'error': error};
	  }
  
	  
	} else {
	  ctx.status = 400;
	  ctx.body = {
		success: 'error',
		message: '无文件上传'
	  };
	}
  });


//获取图片列表
router.get('/getImgData', async (ctx, next) => {
	const token  = ctx.header.authorization;
	const userToken = await verify(token.split(' ')[1], 'test');
	if(!userToken) ctx.body = { success: false, message: "token验证失败" };
	
	const folderPath = path.join(__dirname, '../public/images');
    const files = await fs.promises.readdir(folderPath);
    const fileList = [];

    for (const file of files) {
      const filePath = path.join(folderPath, file);
      const fileStat = await fs.promises.stat(filePath);
	  const fileData = await fs.promises.readFile(filePath); 

      const fileInfo = {
        name: file,
        size: fileStat.size,
        type: path.extname(file).slice(1),
		path: `data:image/${path.extname(file).slice(1)};base64,${fileData.toString('base64')}`,
      };
      fileList.push(fileInfo);
    }

    ctx.body = { files: fileList };
});

//显示缩略图
router.post('/thumbnail',async ctx => {
	let { thumbnailName } = ctx.request.body;
	const thumbnailPath = `./public/thumbnails/${thumbnailName}`;
	try {
	  if (fs.existsSync(thumbnailPath)) {
		const thumbnailData = fs.readFileSync(thumbnailPath);
		ctx.type = 'application/octet-stream'; // 设置返回二进制文件类型
		ctx.body = thumbnailData;
	  } else {
		ctx.body = { status:404, msg:'thumbnail not found'};
	  }
	} catch (err) {
	  console.error('Error:', err);
	  ctx.body  = { status:500,msg:'Error reading the image file'};
	}
  })


//pdf文件管理
router.get('/getFileData', async ctx => {
	const token  = ctx.header.authorization;
	const userToken = await verify(token.split(' ')[1], 'test');
	if(!userToken) ctx.body = { success: false, message: "token验证失败" };
	
	const folderPath = path.join(__dirname, '../public/pdfs');
    const files = await fs.promises.readdir(folderPath);
    const fileList = [];

    for (const file of files) {
      const filePath = path.join(folderPath, file);
      const fileStat = await fs.promises.stat(filePath);

      const fileInfo = {
        name: file,
        size: fileStat.size,
        type: path.extname(file).slice(1),
      };
      fileList.push(fileInfo);
    }

    ctx.body = { files: fileList };
  })

router.delete('/deletePDF', async (ctx, next) => {
	const token  = ctx.header.authorization;
	const userToken = await verify(token.split(' ')[1], 'test');
	if(!userToken) ctx.body = { success: false, message: "token验证失败" };

	const fileName = ctx.query.name;
    const filePath = path.join(__dirname,`../public/pdfs/${fileName}`);
    await fs.promises.unlink(filePath)

	let sqlStr = ("delete from files where name=?");
	let result = ctx.db.Excute(sqlStr, [fileName]);
	if (result) ctx.body = { success: true, message: '文件删除成功' };
	else ctx.body = { success: false, message: '文件删除失败' };

	ctx.body = { success: true, message: '文件删除成功' };
  })


//删除图片
router.delete('/delFile', async (ctx, next) => {
	const token  = ctx.header.authorization;
	const userToken = await verify(token.split(' ')[1], 'test');
	if(!userToken) ctx.body = { success: false, message: "token验证失败" };

	const fileName = ctx.query.name;
    const filePath = path.join(__dirname,`../public/images/${fileName}`);
    await fs.promises.unlink(filePath)

	let sqlStr = ("delete from files where name=?");
	let result = ctx.db.Excute(sqlStr, [fileName]);
	if (result) ctx.body = { success: true, message: '图片删除成功' };
	else ctx.body = { success: false, message: '图片删除失败' };

	ctx.body = { success: true, message: '图片删除成功' };
});

//获取物流路线列表
router.get('/getLogisticsList', async (ctx, next) => {
	const token  = ctx.header.authorization;
	const userToken = await verify(token.split(' ')[1], 'test');
	if(!userToken) ctx.body = { success: false, message: "token验证失败" };
	
	let result = await ctx.db.Excute("select * from transportslines order by onTop desc");
	console.log(result);
    ctx.body = { logisticsList: result };
});

//添加物流路线
router.post('/addLogistics', async (ctx, next) => {
	const token  = ctx.header.authorization;
	const userToken = await verify(token.split(' ')[1], 'test');
	if(!userToken) ctx.body = { success: false, message: "token验证失败" };

	const formDataValue = ctx.request.body;
	const name = formDataValue.name;
	const pathBy = formDataValue.pathBy;
	const address = formDataValue.address;
	const phone = formDataValue.phone;

	let sqlStr = "insert into transportslines (name, pathBy, address, phone) values (?, ?, ?, ?)";
	let result = ctx.db.Excute(sqlStr, [name, pathBy, address, phone]);
	if (result) ctx.body = { success: true, message: '物流路线添加成功' };
	else ctx.body = { success: false, message: '物流路线添加失败' };
})

//置顶物流路线
router.put('/topLine',async(ctx)=>{
	//查询是否被置顶
	let sqlStr1 = "select `onTop` from transportslines where id=?"
	try {

		let {id} = ctx.request.body;
		let results = await ctx.db.Excute(sqlStr1, [id]);
		let sqlStr = "update transportslines set onTop=? where id=?";
		let onTop = results[0].onTop;
		if(onTop==0){
			try {
				let results1 = await ctx.db.Excute(sqlStr, [1, id]);
				if (results1) {
					ctx.body = {success: true, msg: '置顶成功'};
				} else {
					ctx.body = {success: false, msg: '置顶失败'};
				}
			} catch (error) {
				console.log(error);
				ctx.body = '失败';
			}
	  	} else {
			try {
				let results2 = await ctx.db.Excute(sqlStr, [0, id]);
				if (results2) {
					ctx.body = {success: true, msg: '置顶成功'};
				} else {
					ctx.body = {success: false, msg: '置顶失败'};
				}
			} catch (error) {
				console.log(error);
				ctx.body = '取消失败';
			}
		}
	} catch (error) {
	  ctx.body = error
	  console.log(error);
	}
  })


//编辑（修改）
router.put('/updateLogistics', async(ctx, next) => {
	const token  = ctx.header.authorization;
	const userToken = await verify(token.split(' ')[1], 'test');
	if(!userToken) ctx.body = { success: false, message: "token验证失败" };

	const formDataValue = ctx.request.body;
	const name = formDataValue.name;
	const pathBy = formDataValue.pathBy;
	const address = formDataValue.address;
	const phone = formDataValue.phone;

	let sqlStr = "update transportslines set pathBy=?, address=?, phone=? where name=?" 
	let result = ctx.db.Excute(sqlStr, [pathBy, address, phone, name]);
	if (result) ctx.body = { success: true, message: '物流路线修改成功' };
	else ctx.body = { success: false, message: '物流路线修改失败' };
})

//删除物流路线
router.delete('/delLogistics', async (ctx, next) => {
	const token  = ctx.header.authorization;
	const userToken = await verify(token.split(' ')[1], 'test');
	if(!userToken) ctx.body = { success: false, message: "token验证失败" };
	
	const name = ctx.query.name;
	let sqlStr = ("delete from transportslines where name=?");
	let result = ctx.db.Excute(sqlStr, [name]);
	if (result) ctx.body = { success: true, message: '物流路线删除成功' };
	else ctx.body = { success: false, message: '物流路线删除失败' };
});

module.exports = router